package com.huan.gateway.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;

@RestController
@Slf4j
public class TestController {

    @GetMapping(value = "/testMono")
    public Mono<String> testMono() throws InterruptedException {
        log.info("start....");

        Mono<String> mono = Mono.fromSupplier(this::createStr);
        log.info("end ....");
        return mono;
    }

    public String createStr(){
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "testMono";
    }
    @GetMapping(value = "/testFlux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> testFlux() throws InterruptedException {
        log.info("start....");

        List<String> list = new ArrayList<>();
        list.add("1111");
        list.add("2222");
        list.add("3333");
        list.add("4444");
        Flux<String> flux = Flux.fromStream(new Supplier<Stream<? extends String>>() {
            @Override
            public Stream<? extends String> get() {
                return list.stream();
            }
        }).map(new Function<String, String>() {
            @Override
            public String apply(String s) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return "testFlux:" + s;
            }
        });
        log.info("end ....");
        return flux;
    }
}
